﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Bookmark
{
    public class Plugin : Plugins.IPlugin
    {
        #region IPlugin Members
        public string Name { get { return "Bookmark"; } }
        public MSNPSharp.Messenger Messenger { get; set; }
        public List<string> Command
        {
            get { return new List<string> { "bmk", "b", "bmklist", "bl" }; }
        }
        public string RootStore { get; set; }
        public string Chat(string Command, string UserID, string Input)
        {
            if (Command == "bmklist" || Command =="b")
            {
                System.Text.StringBuilder sb = new StringBuilder();
                foreach (BookmarkItem bmk in RetreiveList(UserID))
                {
                    sb.Append(bmk.ToString());
                    sb.Append("\n");
                }
                return sb.ToString();
            }
            else
            {
                RememberData(UserID, Input);
                return "Go it.";
            }
        }
        
        private string UserStore(string UserID)
        {
            string userStore = System.IO.Path.Combine(RootStore, UserID);
            if (!System.IO.Directory.Exists(userStore)) System.IO.Directory.CreateDirectory(userStore);
            userStore = System.IO.Path.Combine(userStore, "BookmarkService");
            if (!System.IO.Directory.Exists(userStore)) System.IO.Directory.CreateDirectory(userStore);
            return userStore;
        }
        private void RememberData(string UserID, string Input)
        {
            BookmarkItem item = new BookmarkItem();
            item.Date = DateTime.Now;
            item.Data = Input;
            string file = System.IO.Path.Combine(UserStore(UserID), System.Guid.NewGuid() + ".bmk");
            Plugins.Serialize.SerializeXMLToDisk(item, file);
        }
        private List<BookmarkItem> RetreiveList(string UserID)
        {
            List<BookmarkItem> list = new List<BookmarkItem>();
            foreach (string file in System.IO.Directory.GetFiles(UserStore(UserID), "*.bmk"))
            {
                BookmarkItem item = (Plugins.Serialize.DeserializeXMLFromDisk(file, typeof(BookmarkItem)) as BookmarkItem);
                if (item != null)
                {
                    list.Add(item);
                }
            }
            return list;
        }
        #endregion
    }
}
